﻿using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace YanZhiwei.DotNet3._5.Utilities.WPF
{
    /// <summary>
    /// WPF-IMAGE控件帮助类
    /// </summary>
    public static class ImageHelper
    {
        #region 设置IMAGE控件图片路径【线程安全】
        /// <summary>
        /// 设置IMAGE控件图片路径【线程安全】
        /// </summary>
        /// <param name="image">Image</param>
        /// <param name="path">图片路径</param>
        public static void SetImagePathTF(this Image image, string path)
        {
            image.Dispatch(img => img.Source = new BitmapImage(new Uri(path, UriKind.Relative)));
        }
        #endregion 
        #region  设置IMAGE控件图片路径【线程安全】
        /// <summary>
        /// 设置IMAGE控件图片路径【线程安全】
        /// </summary>
        /// <param name="image">Image</param>
        /// <param name="path">图片路径</param>
        /// <param name="condition">成立条件</param>
        public static void SetImagePathTF(this Image image, string path, bool condition)
        {
            if (condition)
            {
                SetImagePathTF(image, path);
            }
        }
        /// <summary>
        ///  设置IMAGE控件图片路径【线程安全】
        /// </summary>
        /// <param name="image">Image</param>
        /// <param name="path">图片路径</param>
        /// <param name="conditionHanlder">委托</param>
        public static void SetImagePathTF(this Image image, string path, Func<Image, bool> conditionHanlder)
        {
            if (conditionHanlder(image))
            {
                SetImagePathTF(image, path);
            }
        }
        #endregion 
        #region 将图片二进制数组转换成BitmapSource
        /// <summary>
        /// 将图片二进制数组转换成BitmapSource
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <returns>BitmapSource</returns>
        public static BitmapSource ToBitmapSource(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                var _decoder = BitmapDecoder.Create(ms,
                    BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                return _decoder.Frames[0];
            }
        }
        #endregion 
    }
}
